package org.chmodke.proxy.socks.handle;

import org.chmodke.proxy.socks.util.P;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @author kehao
 * @version 1.0
 * @date 2019/3/17 22:18
 */
public class Socks4Handle {
    private static final Logger logger = LoggerFactory.getLogger(Socks4Handle.class);
    private String proxyHost;
    private Integer proxyPort;

    private String remoteHost;
    private Integer remotePort;
    private Socket proxySocket;

    public Socks4Handle(String proxyHost, Integer proxyPort, String remoteHost, Integer remotePort) {
        this.proxyHost = proxyHost;
        this.proxyPort = proxyPort;
        this.remoteHost = remoteHost;
        this.remotePort = remotePort;
    }

    public Socket connect() throws IOException {
        this.proxySocket = new Socket(proxyHost, proxyPort);
        InputStream proxyInput = proxySocket.getInputStream();
        OutputStream proxyOutput = proxySocket.getOutputStream();

        //连接
        byte[] pushData = new byte[10];
        pushData[0] = P.VER4;//SOCKS4
        pushData[1] = P.V4.CD_CONNECT;//CONNECT
        pushData[2] = (byte) ((remotePort >> 8) & 0xff);//端口
        pushData[3] = (byte) (remotePort & 0xff);
        int i = 3;
        for (String t : remoteHost.split("\\.")) {
            byte temp = (byte) Short.parseShort(t);
            pushData[++i] = temp;//IP
        }
        proxyOutput.write(pushData);
        proxyOutput.flush();

        return proxySocket;
    }

    public void request(String path) throws IOException {
        InputStream proxyInput = proxySocket.getInputStream();
        OutputStream proxyOutput = proxySocket.getOutputStream();
        //开始

        OutputStreamWriter streamWriter = new OutputStreamWriter(proxyOutput);
        BufferedWriter bufferedWriter = new BufferedWriter(streamWriter);
        BufferedInputStream streamReader = new BufferedInputStream(proxyInput);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(streamReader, StandardCharsets.UTF_8));
        bufferedWriter.write("GET /" + path + " HTTP/1.1\r\n");
        bufferedWriter.write("Host: " + remoteHost + "\r\n");
        bufferedWriter.write("\r\n");
        bufferedWriter.flush();

        String line;
        do {
            line = bufferedReader.readLine();
            logger.info(line);
        } while (line != null);
    }
}
